<template>
  <!--新增修改商机页面-->
  <div class="add">
    <!--左边基础资料-->
    <div class="leftcont">
      <div class="return">
        <span @click="returns"><i class="el-icon-back"></i>返回</span>
      </div>
      <el-row>
        <el-col :span="12">
          <div class="info">基础资料</div>
        </el-col>
        <el-col :span="12">
          <div class="info">首要联系人</div>
        </el-col>
      </el-row>
      <el-form :model="cusForm" ref="cusForm" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户负责人:" prop="customEmpid.empName">
              <el-input v-model="cusForm.customEmpid.empName" v-on:click.native="isAdd=true" style="width:240px" title="请点击选择">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人:" prop="culinkmenByCustomId[0].cupName">
              <el-input v-model="cusForm.culinkmenByCustomId[0].cupName" style="width:240px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户名称:" prop="cusName">
              <el-input v-model="cusForm.cusName" style="width:240px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话:" prop="culinkmenByCustomId[0].cupPhone">
              <el-input v-model="cusForm.culinkmenByCustomId[0].cupPhone" oninput="value=value.replace(/[^\d.]/g,'')" style="width:240px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户状态:" prop="typeId">
              <el-input disabled="disabled" style="width: 240px" value="潜在客户"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系地址:" prop="culinkmenByCustomId[0].cupAddressArea">
              <v-distpicker :province="cusForm.culinkmenByCustomId[0].cupAddressProvince" @province="cupChangeProvince"
                            :city="cusForm.culinkmenByCustomId[0].cupAddressCity" @city="cupChangeCity"
                            :area="cusForm.culinkmenByCustomId[0].cupAddressArea" @area="cupChangeArea"
                            class="distpicker-address-wrapper"></v-distpicker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户来源:" prop="cusSource">
              <el-radio-group v-model="cusForm.cusSource">
                <el-radio label="客户介绍"></el-radio>
                <el-radio label="电话访问"></el-radio>
                <el-radio label="其他途径"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址:" prop="culinkmenByCustomId[0].cupXxaddress">
              <el-input v-model="cusForm.culinkmenByCustomId[0].cupXxaddress" style="width:240px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户地址:" prop="cusAddressArea">
              <v-distpicker :province="cusForm.cusAddressProvince" @province="cusChangeProvince"
                            :city="cusForm.cusAddressCity" @city="cusChangeCity"
                            :area="cusForm.cusAddressArea" @area="cusChangeArea"
                            class="distpicker-address-wrapper"></v-distpicker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务:" prop="cupPost">
              <el-input v-model="cusForm.culinkmenByCustomId[0].cupPost" style="width:240px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注:" prop="cusRemark">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="cusForm.cusRemark" style="width:240px">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别:" prop="cupSex">
              <el-radio-group v-model="cusForm.culinkmenByCustomId[0].cupSex">
                <el-radio label="男"></el-radio>
                <el-radio label="女"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" style="margin-left: 600px">
            <el-form-item label="邮箱:" oninput="value=value.replace(/[\u4E00-\u9FA5]/g,'')" prop="culinkmenByCustomId[0].cupEmail">
              <el-input v-model="cusForm.culinkmenByCustomId[0].cupEmail" style="width:240px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" style="margin-left: 600px">
            <el-form-item label="备注:" prop="cupRemark">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="cusForm.culinkmenByCustomId[0].cupRemark" style="width:240px" >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
            <!--            &lt;!&ndash;创建用户按钮&ndash;&gt;-->
            <el-button type="primary" @click="confirmAdd('cusForm')" style="margin-left: 40%;margin-bottom: 40px;">保存</el-button>
        </el-row>
      </el-form>
    </div>

    <!--弹框添加客户负责人-->
    <el-dialog
      title="选择负责人"
      :visible.sync="isAdd">
      <el-row>
        <el-col :span="6">
          <el-input
            placeholder="请输入用户名" style="width: 200px;cursor: pointer;margin-bottom: 10px;margin-left: 420px;"
            v-model="input4" clearable onKeypress="javascript:if(event.keyCode == 32)event.returnValue = false;" @change="serchEmp" suffix-icon="el-icon-search" size="small">
          </el-input>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-table :data="userList" height="250" style="width: 100%">
            <el-table-column width="55">
              <template slot-scope="scope">
                <el-radio v-model="empradio" :label="scope.row" @change="getCustomerRow(scope.row)">
                  {{''}}
                </el-radio>
              </template>
            </el-table-column>

            <el-table-column prop="empName" label="员工姓名" width="120">
            </el-table-column>

            <el-table-column prop="deptByDeptsId.deptName" label="所属部门">
            </el-table-column>

            <el-table-column prop="empSex" label="性别">
            </el-table-column>

            <el-table-column prop="empPhone" label="手机号">
            </el-table-column>
          </el-table>
        </el-col>
        <div class="block">
          <el-pagination
            :page-sizes="sizes"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalSize"
            :page-size="pageSize"
            :current-page.sync="currPage"
            @current-change="pageChange"
            @size-change="sizeChange">
          </el-pagination>
        </div>
      </el-row>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" size="small" @click="empOK">确 定</el-button>
          <el-button size="small" @click="isAdd = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import VDistpicker from 'v-distpicker'
export default {
  name: 'CustomerAdd',
  components: { VDistpicker },
  data () {
    // 查询客户名是否存在
    var checkedCusName = (rule, value, callback) => {
      if(this.updateCusName == value){
        // 如果修改客户信息时没有修改客户名称，就不做校验
        callback();
      }else{
        this.$axios.get("http://localhost:8088/vue/select-cusname",{params:{cusName:value}})
          .then(v=>{
            console.log(v.data)
            if(v.data != null && v.data != ""){
              callback(new Error("该客户名已存在，请重新输入"))
            }else{
              callback()
            }
          }).catch()
      }
    };
    // 查询联系人表联系电话是否重复
    var checkedCupPhone = (rule, value, callback) => {
      if(this.updateCupPhone == value){
        // 如果修改联系人信息时没有修改联系人电话，就不做校验
        callback();
      }else{
        this.$axios.get("http://localhost:8088/vue/select-cupphone",{params:{cupPhone:value}})
          .then(v=>{
            console.log(v.data)
            if(v.data != null && v.data != ""){
              callback(new Error("联系电话重复！请重新输入"))
            }else{
              callback()
            }
          }).catch()
      }
    };
    // 校验客户地址
    var checkCusAdress = (rule, value, callback) => {
      if (this.cusArea=="区" || this.cusArea==undefined) {
        return callback(new Error('请输入客户地址'));
      }else{
        callback()
      }
    };
    var checkCupAdress = (rule, value, callback) => {
      if (this.cusForm.culinkmenByCustomId[0].cupAddressArea=="区" || this.cusForm.culinkmenByCustomId[0].cupAddressArea==undefined) {
        return callback(new Error('请输入联系地址'));
      }
    };
    return {
      updateCusName:'',//修改客户时的客户名称
      updateCupPhone:'',//修改客户联系人时的联系人电话
      options: [],
      cusForm: {
        customId:'',//客户id
        cusName: '', // 客户名称
        customEmpid:{//员工对象
          employeesId:'',//员工id
          empName:'' //员工名字
        },
        culinkmenByCustomId:[{//联系人对象
          cupId:'',//联系人id
          cupName: '', // 联系人姓名
          cupPhone: '', // 联系电话
          cupAddressProvince: '', // 省
          cupAddressCity: '', //市
          cupAddressArea: '', //区
          cupXxaddress:'',// 详细地址
          cupPost:'',//联系人职务
          cupEmail:'',//邮箱
          cupSex:'',//性别
          cupRemark: '' // 联系人备注
        }],
        typeId: {// 客户状态对象
          typeId:0,//类型编号
          typeName:'' //类型名称
        },
        cusSource: '客户介绍',//客户来源单选框
        cusAddressProvince:'',//客户地址
        cusAddressCity:'',
        cusAddressArea:'',
        cusRemark: '' // 基础资料备注
      },
      rules:{
        cusName:[
          {required: true, message: '客户名称不能为空!', trigger: 'change' },
          {validator:checkedCusName,trigger: 'change' }
        ],
        'customEmpid.empName':[
          {required:true,message:'请选择负责人',trigger:'change'}
        ],
        cusSource:[
          { required: true, message: '请选择客户来源', trigger: 'change' }
        ],
        'culinkmenByCustomId[0].cupName':[
          {required:true,message:'请输入联系人姓名',trigger:'change'}
        ],
        'culinkmenByCustomId[0].cupPhone':[
          {required:true,message:'请输入联系电话',trigger:'change'},
          { pattern: /^1[3456789]\d{9}$/,message: '请输入正确的联系电话', trigger:'change'},
          {validator:checkedCupPhone,trigger: 'change'}
        ],
        'culinkmenByCustomId[0].cupAddressArea':[
          {required:true,message:'请输入联系地址',trigger:'change'},
          // {validator:checkCupAdress,trigger: 'change'}
        ],
        'culinkmenByCustomId[0].cupXxaddress':[
          {required:true,message:'请输入详细地址',trigger:'change'},
        ],
        'culinkmenByCustomId[0].cupEmail':[
          { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,message: '请输入正确的邮箱', trigger:'change'}
        ],
      },
      input4: '', // 添加负责人的查询
      empradio: '', // 选择负责人单选框
      emp:[], //选中的员工对象
      userList: [],// 员工列表
      multipleSelection: [],
      // 员工分页
      totalSize: 0, //     总条数
      currPage: 1, //     默认第一页
      pageSize: 0, //      页大小
      sizes: [10, 20, 30, 40], // 员工页大小数组
      isAdd: false, // 选择负责人弹框
      cusArea:'',//客户地址校验
      cupArea:'',//联系地址校验
    }
  },
  created: function () {
    this.clearForm();
    if(this.$route.query.customer != null && this.$route.query.customer != ""){
      this.cusForm=this.$route.query.customer
      // 方便校验
      this.updateCusName=this.cusForm.cusName
      this.updateCupPhone=this.cusForm.culinkmenByCustomId[0].cupPhone
    }
    if(this.$route.query.path != null && this.$route.query.path != ""){
      this.clearForm()//点击新增按钮清空表单
    }
    this.pageSize = this.sizes[0] // 默认第一个页大小
    this.initEmp(this.currPage, this.pageSize) // 初始化员工
    this.$axios.get('http://localhost:8088/vue/select-custype')
      .then(v => {
        this.options = v.data
      })
      .catch()
  },
  methods: {
    returns(){ //返回
      this.$router.push({
        path:'/customer'
      })
      this.clearForm()
    },
    initEmp (currPage, pageSize, empName) { // 查询销售部员工
      this.$axios.get('http://localhost:8088/vue/select-emp', {params: {page: currPage, size: pageSize, empName: empName}})
        .then(v => {
          this.userList = v.data.rows
          this.totalSize = v.data.total
        })
        .catch()
    },
    pageChange (page) { // 员工切换页码
      this.initEmp(page, this.pageSize, this.input4)
    },
    sizeChange (pageSize) { // 员工页大小改变
      this.initEmp(1, pageSize, this.input4)
      this.pageSize = pageSize
    },
    serchEmp () { // 员工模糊查询
      this.initEmp(1, this.pageSize, this.input4)
    },
    // 单选按钮
    getCustomerRow (val) {
      this.emp=[]
      this.emp.push(val)
      window.console.log(this.emp)
    },
    empOK(){ // 确定选中员工
      if(this.emp==null || this.emp==""){
        this.$message("请选择负责人")
      }else {
        this.cusForm.customEmpid = this.emp[0] //赋值员工对象
        this.cusForm.customEmpid.empName = this.emp[0].empName //给输入框赋值
        this.isAdd=false
        console.log(this.emp[0])
      }
    },
    // 确认新增联系人客户按钮
    confirmAdd (formName) {
      this.$refs[formName].validate((valid) => {
        console.log("coming...")
          if (valid) {//如果通过验证
            console.log("通过验证")
              this.$axios.post("http://localhost:8088/vue/save-customer",{
                customId:this.cusForm.customId,
                cusName:this.cusForm.cusName,
                customEmpid:this.cusForm.customEmpid,//员工对象
                culinkmenByCustomId:this.cusForm.culinkmenByCustomId,//联系人对象
                typeId:this.cusForm.typeId,//客户类型对象
                cusSource:this.cusForm.cusSource,
                cusRemark:this.cusForm.cusRemark,
                cusAddressProvince:this.cusForm.cusAddressProvince,
                cusAddressCity:this.cusForm.cusAddressCity,
                cusAddressArea:this.cusForm.cusAddressArea,
              })
              .then(()=>{
                if(this.cusForm.customId != "" && this.cusForm.customId != null && this.cusForm.customId != 0){
                  this.$message.success('编辑成功')
                }else{
                  this.$message.success('新增成功')
                }
                this.clearForm()
                // 跳转页面
                this.$router.push({
                  path:'/customer',
                })
              })
              .catch()
          } else {
            console.log("不通过验证")
            console.log('error submit!!');
            // return false;
          }
      });
    },
    cupChangeProvince(a){//省
      this.cusForm.culinkmenByCustomId[0].cupAddressProvince=a.value
    },
    cupChangeCity(a){//市
      this.cusForm.culinkmenByCustomId[0].cupAddressCity=a.value
    },
    cupChangeArea(a){//区
      this.cusForm.culinkmenByCustomId[0].cupAddressArea=a.value
    },
    cusChangeProvince(a){
      this.cusForm.cusAddressProvince=a.value
    },
    cusChangeCity(a){
      this.cusForm.cusAddressCity=a.value
    },
    cusChangeArea(a){
      this.cusForm.cusAddressArea=a.value
      this.cusArea=this.cusForm.cusAddressArea
    },
    //清空表单
    clearForm(){
      this.cusForm={
        customId:'',//客户id
        cusName: '', // 客户名称
        customEmpid:{//员工对象
          employeesId:'',//员工id
          empName:'' //员工名字
        },
        culinkmenByCustomId:[{//联系人对象
          cupId:'',//联系人id
          cupName: '', // 联系人姓名
          cupPhone: '', // 联系电话
          // value2: '', // 联系时间
          cupAddressProvince: '', // 省
          cupAddressCity: '', //市
          cupAddressArea: '', //区
          cupXxaddress:'',// 详细地址
          cupPost:'',//联系人职务
          cupEmail:'',//邮箱
          cupSex:'男',//性别
          cupRemark: '' // 联系人备注
        }],
        typeId: {// 客户状态对象
          typeId:0,//类型编号
          typeName:'' //类型名称
        },
        cusSource:'客户介绍',//客户来源单选框
        cusRemark: '' // 基础资料备注
      }
    }
  },
  watch:{
    $route(){//带参数跳到该页面后
      if(this.$route.query.customer != null && this.$route.query.customer != ""){
        this.cusForm=this.$route.query.customer
        // 方便校验
        this.updateCusName=this.cusForm.cusName
        this.updateCupPhone=this.cusForm.culinkmenByCustomId[0].cupPhone
      }
      if(this.$route.query.path != null && this.$route.query.path != ""){
        this.clearForm()//点击新增按钮清空表单
      }
    }
  }
}
</script>

<style scoped>
  .add{
    border:1px solid #ccc;
    width:100%;
    background: white;
    border-radius: 5px;
    box-shadow:#ccc 0px 0px 10px;
    overflow:hidden;
    min-height: 650px;
  }

  .leftcont{
    /*width:100%;*/
    /*border-right:1px dashed #ccc;*/
    /*float: left;*/
  }

  .el-form{
    margin-left: 70px;
    margin-top: 8px;
  }

  .rightcont{
    width:50%;
    float: left;
  }

  .info{
    color:#777;
    font-size:14px;
    border-left: 6px solid #409eff;
    width:80px;
    height:24px;
    text-align: center;
    margin-top: 15px;
    margin-left: 30px;
  }

  .add .return{
    border-right:1px solid #ccc;
    width:70px;
    color:#777;
    font-size: 13px;
    margin-left:10px;
    margin-top:10px;
    cursor: pointer;
  }

  .add .return:hover{
    color:#409eff;
  }

  .block{
    float: right;
    margin-top: 10px;
    margin-right: 20px;
  }

  a{
    text-decoration: none;
    color:black;
  }

  a:active{
    color: #333333;
  }

</style>
<style>
  .distpicker-address-wrapper select {
    width: 95px;
  }
</style>
